package com.ruoyi.common.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * 时间工具类
 * 
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
    public static String YYMMDDHHMMSS = "yyMMddHHmmss";
    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
    public static String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";

    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYMMDD = "yyMMdd";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }
    /**
     * 获得当前时间（Timestamp类型）
     */
    public static Timestamp getNewTimestamp() {
        return new Timestamp(new Date().getTime());
    }
    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * @param startDate 格式yyyy-MM-dd
     * @param endDate   格式yyyy-MM-dd
     * @return
     * @function：两个日期相隔天数2014-03-26、2014-03-26=0；2014-03-25、2014-03-26=1
     * @returnType：long
     * @author：xupeng
     * @createTime：Mar 26, 2014
     */
    public static long diffDays(java.util.Date startDate, java.util.Date endDate) {
        try {
            startDate = parseDate(DateFormatUtils.format(startDate, YYYY_MM_DD), YYYY_MM_DD);
            endDate = parseDate(DateFormatUtils.format(endDate, YYYY_MM_DD), YYYY_MM_DD);
        } catch (ParseException e) {
        }
        Calendar startCalendar1 = Calendar.getInstance();
        Calendar endCalendar2 = Calendar.getInstance();
        startCalendar1.setTime(startDate);
        endCalendar2.setTime(endDate);
        long startTime1 = startCalendar1.getTimeInMillis();
        long endTime2 = endCalendar2.getTimeInMillis();
        long result = (endTime2 - startTime1) / (1000 * 60 * 60 * 24);
        return result;
    }

    public static void main(String[] args) {
        System.out.println(parseDateToStr("yyMMdd", getNowDate()));
    }

    /**
     * 格式化输出日期
     *
     * @param date   日期
     * @param format 格式
     * @return 返回字符型日期
     */
    public static String format(Date date, String format) {
        try {
            if (date == null) {
                return null;
            }
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(date);
        } catch (Exception e) {
//            long.error("format exception", e);
            return null;
        }
    }
    /**
     * 格式化对象
     */
//    public final static SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd");
    /**
     * 获取当月第一天
     *
     * @return
     */
    public static String getCurrentMonthFirstDayStr() {
        return new SimpleDateFormat("yyyy-MM-dd").format(getCurrentMonthFirstDay());
    }

    /**
     * 获取当月最后一天
     *
     * @return
     */
    public static String getCurrentMonthLastDayStr() {
        return new SimpleDateFormat("yyyy-MM-dd").format(getCurrentMonthLastDay());
    }
    /**
     * 获取当月第一天
     *
     * @return
     */
    public static Date getCurrentMonthFirstDay() {
        Calendar cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, 0);
        cale.set(Calendar.DAY_OF_MONTH, 1);
        return cale.getTime();
    }

    /**
     * 获取当月最后一天
     *
     * @return
     */
    public static Date getCurrentMonthLastDay() {
        Calendar cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, 1);
        cale.set(Calendar.DAY_OF_MONTH, 0);
        return cale.getTime();
    }


    /**
     * 获取当前时间某月的第一天
     *
     * @param amount 为0时，则为当月的第一天
     * @return
     */
    public static Date getMonthFirstDay(int amount) {
        Calendar cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, amount);
        cale.set(Calendar.DAY_OF_MONTH, 1);
        return cale.getTime();
    }

    /**
     * 获取当前时间某月的最后一天
     *
     * @param amount 为0时，则为当月的最后一天
     * @return
     */
    public static Date getMonthLastDay(int amount) {
        Calendar cale = Calendar.getInstance();
        cale.add(Calendar.MONTH, amount + 1);
        cale.set(Calendar.DAY_OF_MONTH, 0);
        return cale.getTime();
    }

    /**
     * 获取当前时间某月的第一天
     *
     * @param amount 为0时，则为当月的第一天
     * @return
     */
    public static String getMonthFirstDayStr(int amount) {
        return DateUtils.format(getMonthFirstDay(amount), YYYY_MM_DD);
    }

    /**
     * 获取当前时间某月的最后一天
     *
     * @param amount 为0时，则为当月的最后一天
     * @return
     */
    public static String getMonthLastDayStr(int amount) {
        return DateUtils.format(getMonthLastDay(amount), YYYY_MM_DD);
    }

    public static Date getNextMonthDate(Date prevDate, Date firstDate) {
        if (prevDate == null)
            return null;
        GregorianCalendar calendar = (GregorianCalendar) GregorianCalendar
                .getInstance();
        calendar.setTime(prevDate);
        calendar.add(Calendar.MONTH, 1);
        if (null != firstDate) {
            if (calendar.getActualMaximum(Calendar.DAY_OF_MONTH) <= firstDate.getDate()) {
                calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            } else {
                int days = firstDate.getDate() - prevDate.getDate();
                calendar.add(Calendar.DATE, days);
            }
        }
        return calendar.getTime();
    }
    /**
     * 给日期时间增加分钟数
     *
     * @param date 日期
     * @param i    分钟数
     * @return
     */
    public static Date addMinute(Date date, int i) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, i);
        return calendar.getTime();
    }

}
